<template>
  <div class="profile-info">
    <a-card :bordered="false">
      <template #title>{{ t('profile.info.title') }}</template>
      
      <a-descriptions :column="{ xxl: 2, xl: 2, lg: 2, md: 1, sm: 1, xs: 1 }">
        <a-descriptions-item :label="t('profile.username')">
          {{ userInfo.username }}
        </a-descriptions-item>
        <a-descriptions-item :label="t('profile.nickname')">
          {{ userInfo.nickname }}
        </a-descriptions-item>
        <a-descriptions-item :label="t('profile.email')">
          {{ userInfo.email || '-' }}
        </a-descriptions-item>
        <a-descriptions-item :label="t('profile.phone')">
          {{ userInfo.phone || '-' }}
        </a-descriptions-item>
        <a-descriptions-item :label="t('profile.department')">
          {{ userInfo.deptName || '-' }}
        </a-descriptions-item>
        <a-descriptions-item :label="t('profile.role')">
          {{ (userInfo.roleNames?.join(', ')) || (userInfo.roles?.join(', ')) || '-' }}
        </a-descriptions-item>
        <a-descriptions-item :label="t('profile.createTime')">
          {{ formatDate(userInfo.createTime) }}
        </a-descriptions-item>
        <a-descriptions-item :label="t('profile.lastLoginTime')">
          {{ formatDate(userInfo.lastLoginTime) }}
        </a-descriptions-item>
      </a-descriptions>
    </a-card>
    
    <a-card :bordered="false" class="security-card">
      <template #title>{{ t('profile.info.securitySettings') }}</template>
      
      <a-list itemLayout="horizontal">
        <a-list-item>
          <template #actions>
            <a @click="changePassword">{{ t('profile.info.change') }}</a>
          </template>
          <a-list-item-meta
            :title="t('profile.info.loginPassword')"
            :description="t('profile.info.passwordDesc')"
          />
        </a-list-item>
        <a-list-item>
          <template #actions>
            <a @click="bindPhone">{{ userInfo.phone ? t('profile.info.update') : t('profile.info.bind') }}</a>
          </template>
          <a-list-item-meta
            :title="t('profile.info.phoneVerification')"
            :description="userInfo.phone ? userInfo.phone : t('profile.info.notBound')"
          />
        </a-list-item>
        <a-list-item>
          <template #actions>
            <a @click="bindEmail">{{ userInfo.email ? t('profile.info.update') : t('profile.info.bind') }}</a>
          </template>
          <a-list-item-meta
            :title="t('profile.info.emailVerification')"
            :description="userInfo.email ? userInfo.email : t('profile.info.notBound')"
          />
        </a-list-item>
      </a-list>
    </a-card>
    
    <!-- 密码修改弹窗 -->
    <a-modal
      :title="t('profile.changePassword')"
      v-model:open="passwordModalVisible"
      @ok="handlePasswordChange"
      :confirmLoading="confirmLoading"
      :ok-text="t('common.submit')"
      :cancel-text="t('common.cancel')"
    >
      <a-form
        ref="passwordFormRef"
        :model="passwordForm"
        :rules="passwordRules"
        :label-col="{ span: 6 }"
        :wrapper-col="{ span: 16 }"
      >
        <a-form-item name="oldPassword" :label="t('profile.info.oldPassword')">
          <a-input-password v-model:value="passwordForm.oldPassword" />
        </a-form-item>
        <a-form-item name="newPassword" :label="t('profile.info.newPassword')">
          <a-input-password v-model:value="passwordForm.newPassword" />
        </a-form-item>
        <a-form-item name="confirmPassword" :label="t('profile.info.confirmPassword')">
          <a-input-password v-model:value="passwordForm.confirmPassword" />
        </a-form-item>
      </a-form>
    </a-modal>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive } from 'vue'
import { useI18n } from 'vue-i18n'
import type { FormInstance } from 'ant-design-vue'
import { message } from 'ant-design-vue'
import { useAuthStore } from '@/stores/auth'
import { changePassword as changePasswordApi } from '@/api/auth'

// 定义组件名
defineOptions({
  name: 'ProfileInfo'
})

// 国际化
const { t } = useI18n()

// 获取用户store
const authStore = useAuthStore()
const userInfo = authStore.userInfo || {
  username: '',
  nickname: '',
  email: '',
  phone: '',
  deptName: '',
  roles: [] as string[],
  roleNames: [] as string[],
  createTime: '',
  lastLoginTime: ''
}

// 日期格式化
const formatDate = (date: string | undefined) => {
  if (!date) return '-'
  return new Date(date).toLocaleString()
}

// 修改密码相关
const passwordModalVisible = ref(false)
const confirmLoading = ref(false)
const passwordFormRef = ref<FormInstance>()
const passwordForm = reactive({
  oldPassword: '',
  newPassword: '',
  confirmPassword: ''
})

// 表单验证规则
const validateConfirmPassword = async (_rule: any, value: string) => {
  if (value !== passwordForm.newPassword) {
    return Promise.reject(t('profile.info.passwordNotMatch'))
  }
  return Promise.resolve()
}

const passwordRules = {
  oldPassword: [
    { required: true, message: t('profile.info.oldPasswordRequired'), trigger: 'blur' }
  ],
  newPassword: [
    { required: true, message: t('profile.info.newPasswordRequired'), trigger: 'blur' },
    { min: 6, message: t('profile.info.passwordMinLength'), trigger: 'blur' }
  ],
  confirmPassword: [
    { required: true, message: t('profile.info.confirmPasswordRequired'), trigger: 'blur' },
    { validator: validateConfirmPassword, trigger: 'blur' }
  ]
}

// 打开修改密码弹窗
const changePassword = () => {
  passwordForm.oldPassword = ''
  passwordForm.newPassword = ''
  passwordForm.confirmPassword = ''
  passwordModalVisible.value = true
}

// 提交密码修改
const handlePasswordChange = () => {
  passwordFormRef.value?.validate().then(async () => {
    confirmLoading.value = true
    
    try {
      // 调用修改密码API
      const res = await changePasswordApi(
        passwordForm.oldPassword,
        passwordForm.newPassword
      )
      
      if (res && res.success) {
        message.success(t('profile.info.passwordChangeSuccess'))
        passwordModalVisible.value = false
        // 清空表单
        passwordForm.oldPassword = ''
        passwordForm.newPassword = ''
        passwordForm.confirmPassword = ''
      }
    } catch (error) {
      console.error('密码修改失败:', error)
      message.error(t('profile.info.passwordChangeFailed'))
    } finally {
      confirmLoading.value = false
    }
  })
}

// 绑定手机号
const bindPhone = () => {
  message.info('手机绑定功能待实现')
}

// 绑定邮箱
const bindEmail = () => {
  message.info('邮箱绑定功能待实现')
}
</script>

<style lang="scss" scoped>
.profile-info {
  .security-card {
    margin-top: $spacing-md;
  }
}
</style> 